package com.baiyinet.util.task;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;

import com.baiyinet.rest.CustomTrust;
import com.baiyinet.rest.UnSafeHostnameVerifier;
import com.baiyinet.ui.share.ShareModeDialogActivity;
import com.baiyinet.util.Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;

public class OneKeyDownloadImageTask extends AsyncTask<List<String>, Void, Boolean> {

    private static final String SAVE_PATH = Environment.getExternalStorageDirectory() + "/商品图片/";

    private Activity mActivity;

    private CustomTrust mCustomTrust;

    private Dialog mDialog;

    private List<String> mListPath = new ArrayList<>();

    public OneKeyDownloadImageTask(Activity activity, Dialog dialog) {
        mActivity = activity;
        mDialog = dialog;
        mCustomTrust = new CustomTrust(activity);
    }

    @Override
    protected Boolean doInBackground(List<String>... params) {
        List<String> imgs = params[0];
        return downloadAction(imgs);
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }

        if(aBoolean) {
            Utils.UI.showToastShort("图片已保存到SD存储卡的\"商品图片\"目录");
        }else {
            Utils.UI.showToastShort("图片保存失败");
        }

        if(null != mCallBack) {
            mCallBack.onSuccess(mListPath);
        }

    }

    private boolean downloadAction(List<String> imgs) {
        if(null == imgs || 0 == imgs.size()){
            return false;
        }

        if(!Utils.Network.isNetworkAvailable()){
            return false;
        }

        Bitmap bitmap;

        for(String url : imgs) {
            bitmap = null;
            String fileName = url.substring(url.lastIndexOf("/") + 1,url.lastIndexOf("?"));
            File f = new File(SAVE_PATH, fileName);

            // BUG: 在某些机型中无法刷新图片时间?
            if (false) {
//            if (f.exists()) {
                f.setLastModified(new Date().getTime());
                // 发送相册广播
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(f);
                intent.setData(uri);
                mActivity.sendBroadcast(intent);

                mListPath.add(f.getAbsolutePath());
            } else {
                try {
                    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
                    httpClientBuilder
                            .connectTimeout(10, TimeUnit.SECONDS)
                            .writeTimeout(10, TimeUnit.SECONDS)
                            .readTimeout(30, TimeUnit.SECONDS);

                    if (!TextUtils.isEmpty(url) && url.startsWith("https")) {
                        // 添加https
                        httpClientBuilder
                                .sslSocketFactory(mCustomTrust.sslSocketFactory, mCustomTrust.trustManager)
                                .hostnameVerifier(new UnSafeHostnameVerifier());
                    }

                    OkHttpClient httpClient = httpClientBuilder.build();
                    Request request = new Request.Builder().url(url).build();
                    Response response = httpClient.newCall(request).execute();
                    if (response.isSuccessful()) {
                        InputStream is = response.body().byteStream();
//                        bitmap = BitmapFactory.decodeStream(is);
                        saveInputStream(readStream(is),fileName);
                    } else {
                        Timber.e(response.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                if (bitmap == null) {
//                    continue;
//                }
//                saveBitmap(bitmap, fileName);
            }
        }
        return true;
    }

    public byte[] readStream(InputStream inStream) throws Exception{
        //把数据读取存放到内存中去
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while( (len=inStream.read(buffer)) != -1){
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }

    public void saveInputStream(byte[] is, String fileName) {
        File saveFileDir = new File(SAVE_PATH);
        if(!saveFileDir.exists()) {
            saveFileDir.mkdirs();
        }

        File f = new File(SAVE_PATH, fileName);
        if (f.exists()) {
            f.delete();
        }

        try {
            FileOutputStream out = new FileOutputStream(f);
            out.write(is);
            out.flush();
            out.close();

            mListPath.add(f.getAbsolutePath());

            // 发送相册广播
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(f);
            intent.setData(uri);
            mActivity.sendBroadcast(intent);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存方法
     * @param bmp
     **/
    public void saveBitmap(Bitmap bmp, String fileName) {
        File saveFileDir = new File(SAVE_PATH);
        if(!saveFileDir.exists()) {
            saveFileDir.mkdirs();
        }

        File f = new File(SAVE_PATH, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.contains(".jpg") || fileName.contains(".jpeg")) {
                bmp.compress(Bitmap.CompressFormat.JPEG, 93, out);
            }else if (fileName.contains(".png")) {
                bmp.compress(Bitmap.CompressFormat.PNG,100,out);
            }else {
                bmp.compress(Bitmap.CompressFormat.JPEG, 93, out);
            }

            out.flush();
            out.close();
            mListPath.add(f.getAbsolutePath());

            // 发送相册广播
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(f);
            intent.setData(uri);
            mActivity.sendBroadcast(intent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private ImagesSaveCallBack mCallBack;
    /**
     * 设置图片下载回调
     * @param callBack
     */
    public void setImagesSaveCallBack(ImagesSaveCallBack callBack) {
        this.mCallBack = callBack;
    }

    /**
     * 图片保存回调
     */
    public interface ImagesSaveCallBack {
        /**
         * 成功回调
         * @param list
         */
        void onSuccess(List<String> list);
    }
}
